package com.youmu.maven.emall.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.youmu.maven.emall.dao.RoleDao;
import com.youmu.maven.emall.dao.UserDao;
import com.youmu.maven.emall.entity.User;
import com.youmu.maven.emall.service.IUserService;
import com.youmu.maven.emall.service.support.BaseService;

@Service
public class UserService extends BaseService implements IUserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;

	@Override
	public Page<User> queryUser(User user, int page, int rows) {
		PageHelper.startPage(page, rows);
		Map<String, Object> map = initParam(user);
		return userDao.getUsersByPage(map);
	}

	@Override
	public List<User> queryUserFull(User user) {
		List<User> users = userDao.getUsers(initParam(user));

		for (User u : users) {
			fullUser(u);
		}
		return users;
	}

	public void fullUser(User user) {
		user.setRoles(roleDao.getRoleByUserId(user.getId()));
	}

	@Override
	public User queryUserFullById(Long id, boolean throwException) {
		User user = new User();
		user.setId(id);
		Map<String, Object> map = initParam(user);
		List<User> list = userDao.getUsers(map);
		user = (User) getOne(list, throwException);
		if (user == null) {
			return null;
		}
		fullUser(user);
		return user;
	}

	@Override
	public void deleteUserById(Long id) {
		if (id == null)
			throw new RuntimeException("Null id to delete");
		User user = new User();
		user.setId(id);
		userDao.deleteUser(initParam(user));
	}

	@Override
	public Long insertUser(User user) {
		return userDao.insertUser(initParam(user));
	}

	@Override
	public void updateUser(User user) {
		if (user.getId() == null)
			throw new RuntimeException("Null id to update");
		userDao.updateUser(initParam(user));
	}
}
